package io.elegant

import android.content.Context
import android.widget.Toast
import com.google.protobuf.*
import com.google.protobuf.Any
import io.elegant.Elegant.Interaction

typealias KtAny = kotlin.Any?
private val boolBuilder = BoolValue.newBuilder()
private val bytesBuilder = BytesValue.newBuilder()
private val stringBuilder = StringValue.newBuilder()
private val intBuilder = Int32Value.newBuilder()
private val longBuilder = Int64Value.newBuilder()
private val floatBuilder = FloatValue.newBuilder()
private val doubleBuilder = DoubleValue.newBuilder()
private val emptyBuilder = Empty.newBuilder()
fun KtAny.toAny() = when (this) {
    is ByteArray -> bytesBuilder
        .setValue(ByteString.copyFrom(this))
        .build()
    is String -> stringBuilder
        .setValue(this)
        .build()
    is Int -> intBuilder
        .setValue(this)
        .build()
    is Long -> longBuilder
        .setValue(this)
        .build()
    is Boolean -> boolBuilder
        .setValue(this)
        .build()
    is Float -> floatBuilder
        .setValue(this)
        .build()
    is Double -> doubleBuilder
        .setValue(this)
        .build()
    else -> emptyBuilder.build()
}.let { Any.pack(it) }
fun Any.toBytesValue() = unpack(BytesValue::class.java).value.let {
    ByteArray(it.size()).apply {it.copyTo(this, 0) }
}
fun Any.toIntValue() = unpack(Int32Value::class.java).value
fun Any.toLongValue() = unpack(Int64Value::class.java).value
fun Any.toFloatValue() = unpack(FloatValue::class.java).value
fun Any.toStringValue() = unpack(StringValue::class.java).value
fun Any.toStringValueOrNull() = takeIf { `is`(StringValue::class.java) }?.toStringValue()
fun Any.toBoolValue() = unpack(BoolValue::class.java).value
fun Any.isEmpty() = `is`(Empty::class.java)
fun Any.toInteraction() = takeIf { `is`(Interaction::class.java) }
    ?.unpack(Interaction::class.java)
fun Context.toActivity() = when (this) {
    is ElegantActivity -> this
    else -> null
}
fun Context.toast(msg: String) = Toast
    .makeText(this, msg, Toast.LENGTH_SHORT)
    .show()
